import React, { useState, useEffect } from 'react';
import api from '../../services/api';
import './ProfilePage.css';

function ProfilePage({ user, token, setUser }) {
    const [userInfo, setUserInfo] = useState(null);
    const [editMode, setEditMode] = useState(false);
    const [editFormData, setEditFormData] = useState({});
    const [loading, setLoading] = useState(true);
    const [updateLoading, setUpdateLoading] = useState(false);
    const [invitationCode, setInvitationCode] = useState('');
    const [inviteLoading, setInviteLoading] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });

    // 新增状态
    const [avatarUrl, setAvatarUrl] = useState('');
    const [passkey, setPasskey] = useState('');
    const [avatarLoading, setAvatarLoading] = useState(false);
    const [passkeyLoading, setPasskeyLoading] = useState(false);

    // 添加 token 提取逻辑
    const actualToken = (() => {
        let extractedToken = null;

        // 首先检查传入的 token 是否有效
        if (token && token !== 'undefined' && token !== 'null' && token.trim() !== '') {
            extractedToken = token.trim();
        }
        // 如果传入的 token 无效，尝试从 user.data.token 中提取
        else if (user?.data?.token) {
            extractedToken = user.data.token.trim();
        }

        // 验证 token 格式
        if (extractedToken) {
            console.log('提取到的 token:', extractedToken);
            console.log('Token 长度:', extractedToken.length);
            console.log('Token 开头:', extractedToken.substring(0, 20));
            console.log('Token 结尾:', extractedToken.substring(extractedToken.length - 20));

            // 检查是否是有效的 JWT 格式 (应该有两个点分隔三部分)
            const parts = extractedToken.split('.');
            console.log('Token 分段数量:', parts.length);

            if (parts.length !== 3) {
                console.error('Token 格式不正确，应该有3个部分，实际有:', parts.length);
                return null;
            }

            // 检查每个部分是否是有效的 base64
            for (let i = 0; i < parts.length; i++) {
                if (!parts[i] || parts[i].length === 0) {
                    console.error(`Token 第${i+1}部分为空`);
                    return null;
                }
            }

            return extractedToken;
        }

        return null;
    })();

    useEffect(() => {
        console.log('ProfilePage mounted, props:', { user, token });
        console.log('实际使用的 token:', actualToken);

        if (actualToken) {
            fetchUserInfo();
        } else {
            console.error('Token is missing or invalid!');
            setMessage({ type: 'error', text: '缺少认证信息，请重新登录' });
            setLoading(false);
        }
    }, [actualToken]); // 依赖改为 actualToken

    const fetchUserInfo = async () => {
        try {
            console.log('开始获取用户信息...');
            console.log('使用的 token:', actualToken);
            console.log('Token 长度:', actualToken?.length);
            setLoading(true);

            const result = await api.getUserInfo(actualToken); // 使用 actualToken
            console.log('API返回的完整响应:', result);
            console.log('响应数据类型:', typeof result);
            console.log('响应数据结构:', Object.keys(result || {}));

            // 检查响应是否成功
            if (result && result.status === 301) {
                throw new Error(result.msg || 'TOKEN验证失败');
            }

            // 处理可能的数据结构
            const userData = result.data || result;
            console.log('解析后的用户数据:', userData);

            setUserInfo(userData);
            setEditFormData({
                id: user?.id || user?.data?.id || userData?.id,
                bio: userData?.bio || '',
                school: userData?.school || '',
                college: userData?.college || '',
                age: userData?.age || ''
            });

            console.log('用户信息设置成功');
            console.log('设置的编辑表单数据:', {
                bio: userData?.bio,
                school: userData?.school,
                college: userData?.college,
                age: userData?.age
            });

            // 获取头像和passkey
            await fetchUserAvatar(userData);
            await fetchPasskey();

        } catch (error) {
            console.error('获取用户信息失败，详细错误:', error);
            setMessage({
                type: 'error',
                text: `获取用户信息失败: ${error.message}`
            });
        } finally {
            setLoading(false);
        }
    };

    // 新增：获取用户头像 - 修复路径格式
    const fetchUserAvatar = async (userData) => {
        try {
            setAvatarLoading(true);

            // 【修复】构建正确的头像路径格式
            let avatarPath = '';

            // 首先尝试从用户数据中获取头像路径
            if (userData?.avatarPath && userData.avatarPath.trim() !== '') {
                avatarPath = userData.avatarPath.trim();
            } else if (userData?.avatar && userData.avatar.trim() !== '') {
                avatarPath = userData.avatar.trim();
            } else {
                // 【关键修复】使用正确的路径格式构建默认头像路径
                const userId = userData?.id || user?.id || user?.data?.id;
                if (userId) {
                    avatarPath = `avatar/user${userId}.png`;
                } else {
                    console.warn('无法获取用户ID，跳过头像加载');
                    setAvatarLoading(false);
                    return;
                }
            }

            console.log('=== 获取头像详细信息 ===');
            console.log('用户数据:', userData);
            console.log('用户ID:', userData?.id || user?.id || user?.data?.id);
            console.log('构建的头像路径:', avatarPath);
            console.log('路径格式检查:', avatarPath.includes('avatar/user') ? '✅ 正确' : '❌ 错误');

            const result = await api.getUserAvatar(actualToken, avatarPath);
            console.log('头像API返回结果:', result);
            console.log('返回结果类型:', typeof result);

            if (result) {
                if (result instanceof Blob) {
                    // 如果返回的是Blob对象
                    const url = URL.createObjectURL(result);
                    setAvatarUrl(url);
                    console.log('✅ 头像设置成功 (Blob):', url);
                } else if (typeof result === 'string') {
                    // 如果返回的是base64字符串
                    const imageUrl = result.startsWith('data:') ? result : `data:image/jpeg;base64,${result}`;
                    setAvatarUrl(imageUrl);
                    console.log('✅ 头像设置成功 (Base64)');
                } else if (result.url) {
                    // 如果返回的是包含URL的对象
                    setAvatarUrl(result.url);
                    console.log('✅ 头像设置成功 (URL):', result.url);
                } else if (result.data) {
                    // 如果数据在result.data中
                    if (typeof result.data === 'string') {
                        const imageUrl = result.data.startsWith('data:') ? result.data : `data:image/jpeg;base64,${result.data}`;
                        setAvatarUrl(imageUrl);
                        console.log('✅ 头像设置成功 (Data字段)');
                    }
                } else {
                    console.warn('⚠️ API返回了数据，但格式不识别:', result);
                }
            }
        } catch (error) {
            console.error('❌ 获取头像失败，详细错误:', error);
            console.error('错误类型:', error.name);
            console.error('错误信息:', error.message);

            // 如果是文件不存在的错误，尝试不同的文件扩展名
            if (error.message.includes('404') || error.message.includes('不存在')) {
                console.log('🔄 尝试其他文件格式...');
                try {
                    const userId = userData?.id || user?.id || user?.data?.id;
                    if (userId) {
                        // 尝试不同的文件扩展名
                        const alternativePaths = [
                            `avatar/user${userId}.jpg`,
                            `avatar/user${userId}.jpeg`,
                            `avatar/user${userId}.gif`,
                            `avatar/${userId}.png`,
                            `avatars/user${userId}.png`
                        ];

                        for (const altPath of alternativePaths) {
                            try {
                                console.log('🔄 尝试路径:', altPath);
                                const altResult = await api.getUserAvatar(actualToken, altPath);
                                if (altResult instanceof Blob) {
                                    const url = URL.createObjectURL(altResult);
                                    setAvatarUrl(url);
                                    console.log('✅ 使用备选路径成功:', altPath);
                                    return;
                                }
                            } catch (altError) {
                                console.log('❌ 备选路径失败:', altPath);
                            }
                        }
                    }
                } catch (retryError) {
                    console.log('🔄 所有备选方案都失败，使用默认头像');
                }
            }

            // 如果所有尝试都失败，不显示错误消息，只是使用默认头像占位符
        } finally {
            setAvatarLoading(false);
        }
    };

    // 新增：获取passkey
    const fetchPasskey = async () => {
        try {
            setPasskeyLoading(true);
            console.log('获取passkey...');

            const result = await api.getPasskey(actualToken);
            console.log('Passkey API返回:', result);

            if (result && result.data) {
                setPasskey(result.data);
            } else if (typeof result === 'string') {
                setPasskey(result);
            }
        } catch (error) {
            console.error('获取passkey失败:', error);
            // 不显示错误消息，保持passkey为空
        } finally {
            setPasskeyLoading(false);
        }
    };

    // 复制passkey到剪贴板
    const copyPasskey = async () => {
        try {
            await navigator.clipboard.writeText(passkey);
            setMessage({ type: 'success', text: 'Passkey已复制到剪贴板' });
            // 2秒后清除消息
            setTimeout(() => {
                setMessage({ type: '', text: '' });
            }, 2000);
        } catch (error) {
            console.error('复制失败:', error);
            setMessage({ type: 'error', text: '复制失败，请手动复制' });
        }
    };

    const handleEditInputChange = (e) => {
        const { name, value } = e.target;
        setEditFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleUpdateInfo = async () => {
        setUpdateLoading(true);
        try {
            const updateData = {
                ...editFormData,
                age: editFormData.age ? parseInt(editFormData.age) : undefined
            };

            console.log('更新用户信息，数据:', updateData);
            await api.updateUserInfo(actualToken, updateData); // 使用 actualToken
            setMessage({ type: 'success', text: '用户信息更新成功' });
            setEditMode(false);
            fetchUserInfo(); // 重新获取用户信息
        } catch (error) {
            console.error('更新用户信息失败:', error);
            setMessage({ type: 'error', text: error.message || '更新失败' });
        } finally {
            setUpdateLoading(false);
        }
    };

    const handleGenerateInviteCode = async () => {
        setInviteLoading(true);
        try {
            const result = await api.getInvitationCode(actualToken, 1); // 使用 actualToken
            console.log('生成邀请码结果:', result);

            // 根据API文档，邀请码可能在 result.invitationCode 或 result.data?.invitationCode
            const code = result.invitationCode || result.data?.invitationCode;
            setInvitationCode(code);
            setMessage({ type: 'success', text: '邀请码生成成功' });
        } catch (error) {
            console.error('生成邀请码失败:', error);
            setMessage({ type: 'error', text: error.message || '生成邀请码失败' });
        } finally {
            setInviteLoading(false);
        }
    };

    const formatBytes = (bytes) => {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleDateString('zh-CN');
    };

    const calculateUserLevel = (userInfo) => {
        if (!userInfo) return { level: 1, name: '新晋会员' };

        const {
            magicValue = 0,          // 累计消费的魔力值
            registerTime,            // 注册时间
            totalUpload = 0,         // 总上传量
            totalDownload = 0,       // 总下载量
            lastActiveTime = new Date() // 最后活跃时间
        } = userInfo;

        // 1. 时间系数（注册时长）
        const registerDate = new Date(registerTime);
        const now = new Date();
        const monthsRegistered = (now - registerDate) / (1000 * 60 * 60 * 24 * 30);
        const timeScore = Math.min(monthsRegistered * 0.5, 5); // 最高5分

        // 2. 消费系数（魔力值消费）
        const consumptionScore = Math.min(magicValue / 1000, 10); // 每1000魔力值1分，最高10分

        // 3. 活跃度系数
        const lastActive = new Date(lastActiveTime);
        const daysSinceLastActive = (now - lastActive) / (1000 * 60 * 60 * 24);
        const activityScore = Math.min(1 / (daysSinceLastActive + 1) * 5, 5); // 最高5分

        // 4. 贡献系数（上传/下载比）
        const uploadDownloadRatio = totalUpload / (totalDownload || 1);
        const contributionScore = Math.min(uploadDownloadRatio * 2, 5); // 最高5分

        // 总分计算
        const totalScore = timeScore + consumptionScore + activityScore + contributionScore;

        // 等级划分
        if (totalScore >= 20) return { level: 5, name: '资深会员', score: totalScore };
        if (totalScore >= 15) return { level: 4, name: '高级会员', score: totalScore };
        if (totalScore >= 10) return { level: 3, name: '中级会员', score: totalScore };
        if (totalScore >= 5) return { level: 2, name: '初级会员', score: totalScore };
        return { level: 1, name: '新晋会员', score: totalScore };
    };

    const getLevelStyle = (level) => {
        const styles = {
            1: { color: '#95a5a6', gradient: 'linear-gradient(45deg, #95a5a6, #7f8c8d)' },
            2: { color: '#3498db', gradient: 'linear-gradient(45deg, #3498db, #2980b9)' },
            3: { color: '#2ecc71', gradient: 'linear-gradient(45deg, #2ecc71, #27ae60)' },
            4: { color: '#e67e22', gradient: 'linear-gradient(45deg, #e67e22, #d35400)' },
            5: { color: '#e74c3c', gradient: 'linear-gradient(45deg, #e74c3c, #c0392b)' }
        };
        return styles[level] || styles[1];
    };

    const getLevelDiscount = (level) => {
        const discounts = {
            1: '无折扣',
            2: '95折',
            3: '9折',
            4: '85折',
            5: '8折'
        };
        return discounts[level] || discounts[1];
    };

    const isNewUser = (registerTime) => {
        if (!registerTime) return false;
        const registerDate = new Date(registerTime);
        const now = new Date();
        const threeMonthsAgo = new Date(now.setMonth(now.getMonth() - 3));
        return registerDate > threeMonthsAgo;
    };

    if (loading) {
        return (
            <div className="loading">
                <div className="loading-spinner"></div>
                加载中...
            </div>
        );
    }

    if (!actualToken) { // 改为检查 actualToken
        return (
            <div className="profile-container">
                <div className="card">
                    <p className="text-center text-gray-light">请先登录后再访问个人中心</p>
                </div>
            </div>
        );
    }

    return (
        <div className="profile-container">
            <div className="profile-header">
                <div className="profile-title">
                    <h1>个人中心</h1>
                    <p>管理您的个人信息和账户设置</p>
                </div>
                <button
                    onClick={() => setEditMode(!editMode)}
                    className="edit-btn"
                >
                    {editMode ? '❌ 取消编辑' : '✏️ 编辑信息'}
                </button>
            </div>

            {message.text && (
                <div className={`message ${message.type}`}>
                    {message.text}
                </div>
            )}

            <div className="profile-content">
                {/* 基本信息 */}
                <div className="profile-section">
                    <h2 className="section-title">基本信息</h2>

                    {/* 头像显示 */}
                    <div className="avatar-section">
                        <span className="info-label">👤 头像：</span>
                        <div className="avatar-container">
                            {avatarLoading ? (
                                <div className="avatar-placeholder">
                                    <div className="loading-spinner-small"></div>
                                    <span>加载中...</span>
                                </div>
                            ) : avatarUrl ? (
                                <img
                                    src={avatarUrl}
                                    alt="用户头像"
                                    className="user-avatar"
                                    onError={() => {
                                        console.log('头像加载失败，使用默认头像');
                                        setAvatarUrl('');
                                    }}
                                />
                            ) : (
                                <div className="avatar-placeholder">
                                    <span>🧑‍💼</span>
                                    <span>暂无头像</span>
                                </div>
                            )}
                        </div>
                    </div>

                    <div className="info-item">
                        <span>👤</span>
                        <span className="info-label">用户名：</span>
                        <span className="info-value">
                            {user?.username || user?.data?.username || '未知'}
                            {isNewUser(userInfo.registerTime) && (
                                <span className="new-user-badge">新手</span>
                            )}
                        </span>
                    </div>

                    <div className="info-item">
                        <span>📧</span>
                        <span className="info-label">邮箱：</span>
                        <span className="info-value">{user?.email || user?.data?.email || userInfo?.email || '未知'}</span>
                    </div>

                    <div className="info-item">
                        <span>📅</span>
                        <span className="info-label">注册时间：</span>
                        <span className="info-value">
                            {userInfo?.registerTime ? formatDate(userInfo.registerTime) : '未知'}
                        </span>
                    </div>

                    <div className="info-item">
                        <span>🎂</span>
                        <span className="info-label">年龄：</span>
                        {editMode ? (
                            <input
                                type="number"
                                name="age"
                                value={editFormData.age}
                                onChange={handleEditInputChange}
                                className="info-input"
                                placeholder="输入年龄"
                            />
                        ) : (
                            <span className="info-value">{userInfo?.age || '未设置'}</span>
                        )}
                    </div>

                    <div className="info-item">
                        <span>🏫</span>
                        <span className="info-label">学校：</span>
                        {editMode ? (
                            <input
                                type="text"
                                name="school"
                                value={editFormData.school}
                                onChange={handleEditInputChange}
                                className="info-input"
                                placeholder="输入学校名称"
                            />
                        ) : (
                            <span className="info-value">{userInfo?.school || '未设置'}</span>
                        )}
                    </div>

                    <div className="info-item">
                        <span>📚</span>
                        <span className="info-label">学院：</span>
                        {editMode ? (
                            <input
                                type="text"
                                name="college"
                                value={editFormData.college}
                                onChange={handleEditInputChange}
                                className="info-input"
                                placeholder="输入学院名称"
                            />
                        ) : (
                            <span className="info-value">{userInfo?.college || '未设置'}</span>
                        )}
                    </div>

                    <div className="bio-section">
                        <span className="info-label">📝 个人简介：</span>
                        {editMode ? (
                            <textarea
                                name="bio"
                                value={editFormData.bio}
                                onChange={handleEditInputChange}
                                className="bio-textarea"
                                placeholder="介绍一下自己..."
                            />
                        ) : (
                            <div className="bio-text">
                                {userInfo?.bio || '暂无个人简介'}
                            </div>
                        )}
                    </div>

                    {editMode && (
                        <button
                            onClick={handleUpdateInfo}
                            disabled={updateLoading}
                            className="save-btn"
                        >
                            💾 {updateLoading ? '保存中...' : '保存修改'}
                        </button>
                    )}
                </div>

                {/* 统计信息 */}
                <div className="profile-section">
                    <h2 className="section-title">账户统计</h2>

                    {/* Passkey 显示 */}
                    <div className="passkey-card">
                        <div className="passkey-header">
                            <span>🔑</span>
                            <span>Passkey</span>
                        </div>

                        {passkeyLoading ? (
                            <div className="passkey-loading">
                                <div className="loading-spinner-small"></div>
                                <span>加载中...</span>
                            </div>
                        ) : passkey ? (
                            <div className="passkey-display">
                                <div className="passkey-value" title={passkey}>
                                    {passkey}
                                </div>
                                <button
                                    onClick={copyPasskey}
                                    className="copy-btn"
                                    title="复制Passkey"
                                >
                                    📋
                                </button>
                            </div>
                        ) : (
                            <div className="passkey-placeholder">
                                暂无Passkey
                            </div>
                        )}
                    </div>

                    {userInfo && (
                        <div className="user-level-card">
                            {(() => {
                                const levelInfo = calculateUserLevel(userInfo);
                                const style = getLevelStyle(levelInfo.level);
                                return (
                                    <div className="level-info" style={{ background: style.gradient }}>
                                        <div className="level-badge">
                                            <span className="level-number">Lv.{levelInfo.level}</span>
                                            <span className="level-name">{levelInfo.name}</span>
                                        </div>
                                        <div className="level-details">
                                            <div className="level-score">等级积分：{levelInfo.score.toFixed(1)}</div>
                                            <div className="level-discount">会员折扣：{getLevelDiscount(levelInfo.level)}</div>
                                        </div>
                                    </div>
                                );
                            })()}
                        </div>
                    )}

                    <div className="stats-grid">
                        <div className="stat-card">
                            <div className="stat-icon">⬆️</div>
                            <div className="stat-value">
                                {userInfo?.totalUpload ? formatBytes(userInfo.totalUpload) : '0 B'}
                            </div>
                            <div className="stat-label">总上传</div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon">⬇️</div>
                            <div className="stat-value">
                                {userInfo?.totalDownload ? formatBytes(userInfo.totalDownload) : '0 B'}
                            </div>
                            <div className="stat-label">总下载</div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon">👥</div>
                            <div className="stat-value">
                                {userInfo?.inviteCount || 0}
                            </div>
                            <div className="stat-label">邀请人数</div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-icon">⭐</div>
                            <div className="stat-value">
                                {userInfo?.magicValue || 0}
                            </div>
                            <div className="stat-label">魔法值</div>
                        </div>
                    </div>

                    <div className="invite-card">
                        <div className="invite-header">
                            <span>🎫</span>
                            <span>邀请码管理</span>
                        </div>

                        {invitationCode ? (
                            <div className="invite-code-display">
                                <div className="invite-code-label">您的邀请码：</div>
                                <div className="invite-code-value">{invitationCode}</div>
                            </div>
                        ) : (
                            <div className="invite-placeholder">您还没有生成邀请码</div>
                        )}

                        <button
                            onClick={handleGenerateInviteCode}
                            disabled={inviteLoading}
                            className="invite-btn"
                        >
                            {inviteLoading ? '生成中...' : '生成邀请码'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default ProfilePage;